import pygame

# 初始化 Pygame
pygame.init()

# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)

# 游戏窗口尺寸
WIDTH = 800
HEIGHT = 600

# 创建游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('冒险岛')

# 设置时钟
clock = pygame.time.Clock()

# 设置角色属性
player_size = 50
player_x = WIDTH // 4
player_y = HEIGHT - player_size
player_y_change = 0
is_jumping = False
can_double_jump = False
score = 0

# 陷阱
trap_width = 50
trap_height = 50
traps = []
trap_frequency = 30  # 控制陷阱生成频率
trap_counter = 0  # 控制生成次数


def draw_player(x, y):
    """绘制玩家角色在指定坐标的矩形"""
    pygame.draw.rect(screen, GREEN, (x, y, player_size, player_size))


def draw_trap(x, y):
    """绘制陷阱在指定坐标的矩形"""
    pygame.draw.rect(screen, RED, (x, y, trap_width, trap_height))


def show_score(score):
    """显示游戏得分"""
    font = pygame.font.SysFont("comicsansms", 35)
    score_text = font.render("Score: " + str(score), True, BLACK)
    screen.blit(score_text, [10, 10])


def game_loop():
    """主游戏循环，处理游戏逻辑和渲染"""
    global player_y, player_y_change, is_jumping, can_double_jump, score, trap_counter

    game_over = False
    score = 0
    fall_status = 0

    while not game_over:
        screen.fill(WHITE)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_over = True

            # 控制角色跳跃
            # 处理角色跳跃逻辑，包括第一次跳跃和二次跳跃的条件判断
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    if not is_jumping:  # 第一次跳跃
                        player_y_change = -15
                        is_jumping = True
                        can_double_jump = True  # 允许二次跳跃
                    elif can_double_jump:  # 二次跳跃
                        player_y_change = -10
                        can_double_jump = False

        # 更新角色位置
        # 处理角色的垂直运动，当角色跳跃时更新位置并判断是否落地
        if is_jumping:
            player_y += player_y_change
            player_y_change += 1
            if player_y >= HEIGHT - player_size:
                player_y = HEIGHT - player_size
                is_jumping = False

        draw_player(player_x, player_y)

        # 陷阱生成逻辑
        trap_counter += 1
        if trap_counter >= trap_frequency:
            trap_x = WIDTH
            trap_y = HEIGHT - trap_height
            traps.append([trap_x, trap_y])
            trap_counter = 0  # 重置计数器

        # 更新和绘制陷阱
        for trap in traps:
            trap[0] -= 5  # 陷阱向左移动
            draw_trap(trap[0], trap[1])

            # 检测碰撞
            if (player_x < trap[0] + trap_width and
                    player_x + player_size > trap[0] and
                    player_y + player_size > trap[1]):
                game_over = True

            # 增加得分
            if trap[0] < 0:
                traps.remove(trap)
                score += 1

        show_score(score)
        pygame.display.update()
        clock.tick(30)

    pygame.quit()


game_loop()
